package com.dragon.framework.generator;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * Spring BeanName 生成器
 *
 * <pre>
 * 启动类配置 @ComponentScan 和 @MapperScan
 * *   @ComponentScan(nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class)
 * *   @MapperScan(value = {"**.mapper"}, nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class)
 *  FullyQualifiedAnnotationBeanNameGenerator 可以替换为 SpringBeanNameGenerator
 * </pre>
 *
 * @author dragon
 * @version 1.0
 * @date 2024/7/30 15:31
 */
public class SpringBeanNameGenerator extends AnnotationBeanNameGenerator {

    @NonNull
    @Override
    public String generateBeanName(@NonNull BeanDefinition definition, @NonNull BeanDefinitionRegistry registry) {
        if (definition instanceof AnnotatedBeanDefinition) {
            String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition);
            if (StringUtils.hasText(beanName)) {
                // 找到显式bean名称
                return beanName;
            } else {
                // 全限定类名，包名 + 类名
                return Objects.requireNonNull(definition.getBeanClassName());
            }
        }

        // Fallback: generate a unique default bean name.
        return buildDefaultBeanName(definition, registry);
    }

}
